import express from "express";
import fs from "fs";
import path from "path"
import db from "./../libs/DBhelper";
import md5 from "md5"
let apiRouter = express.Router();

//注册模块
apiRouter.post("/reg", (request, response, next) => {
    //如果有图片则处理图片上传
    // var fileObj = request.files[0];
    // console.log(fileObj)
    //准备sql语句
    let sql = "INSERT INTO `users`(`uname`,`upwd`,`uphone`,`uemail`,`uaddress`) VALUES(?,?,?,?,?)"
    //准备参数
    let params = [
        request.body.uname,
        md5(md5(request.body.upwd) + require("./../libs/Configs").keys), //md5加密
        request.body.uphone,
        request.body.uemail,
        request.body.uaddress
    ]
    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "sql语句有问题!",
                status: -2
            })
            return;
        }
        if (result.affectedRows >= 1) {
            response.json({
                msg: "注册成功!",
                status: 1
            })
        } else {
            response.json({
                msg: "注册失败!",
                status: -1
            })
        }
    })


    //response.end("reg");


    //图片上传
    // let newpath = fileObj.path + path.extname(fileObj.originname)
    // fs.rename(fileObj.path,newpath,(err)=>{
    //     if(err){
    //         response.json({
    //             msg:"图片上传失败!",
    //             err:err.message
    //         })
    //         return;
    //     }else{
    //         //把用户名 密码 图片等上传到数据库

    //     }
    // })


})

//登录模块
apiRouter.post("/login", (request, response, next) => {
    let sql = "SELECT `uid`,`uname`,`uphone`,`uemail`,`uaddress` FROM `users` WHERE ustatus=1 AND uphone=? AND upwd=?";
    let params = [
        request.body.uphone,
        md5(md5(request.body.upwd) + require("./../libs/Configs").keys)
    ]

    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "登陆失败!",
                err: err.message
            })
            return;
        }

        if (result.length >= 1) {
            request.session["users"] = "豹子头零充"
            response.json({
                msg: "登录成功!",
                status: 1,
                data: result[0]
            })
        } else {
            response.json({
                msg: "登陆失败,用户名或密码错误",
                status: -1
            })
        }

    })

})
//退出
apiRouter.get("/quit", (request, response, next) => {
    if (request.session["users"]) {
        request.session["users"] == null;
    }
    response.json({
        msg: "退出成功!",
        status: 1
    })
    //前端把localStorage 的数据清除

})
//产品列表
apiRouter.get("/goods", (request, response, next) => {
    var goodsStr = fs.readFileSync("./data/goods.json", {
        encoding: "utf-8"
    }).toString();
    response.end(goodsStr);
})

//动态进入对应详情页面
apiRouter.get("/goodsinfo/:id", (request, response, next) => {
    var goodsStr = fs.readFileSync("./data/goods.json", {
        encoding: "utf-8"
    }).toString();

    var resultObj = JSON.parse(goodsStr).filter((el) => {
        return el.p_id == request.params.id;
    })
    response.json(resultObj);
})

//加入购物车接口
apiRouter.post("/addcart", (request, response, next) => {
    //异常捕获
    try {
        //根据商品id 和用户id 查询是否存在
        let querySelect = "SELECT * FROM `carts` WHERE u_id=? AND p_id=?;";
        let queryParams = [
            request.body.u_id,
            request.body.p_id
        ];
        db.exec(querySelect, queryParams, (err, queryResult) => {
            //查询返回结果,结果是个数组 length属性
            if (queryResult.length >= 1) {
                var updateSql = "UPDATE `carts` SET p_number=p_number+? , p_total=p_number*p_price WHERE u_id=? AND p_id=? ; ";
                let updatePrams = [
                    request.body.p_number,
                    request.body.u_id,
                    request.body.p_id
                ]
                db.exec(updateSql, updatePrams, (err, updateReulst) => {
                    if (updateReulst.affectedRows == 1) {
                        response.json({
                            msg: "加入购物车成功u",
                            status: 1
                        })
                    } else {
                        response.json({
                            msg: "加入购物车失败u",
                            status: -1
                        })
                    }
                });

            } else {
                let sql = "INSERT INTO `carts` (`u_id`,`p_name`,`p_price`,`p_number`,`p_img`,`p_type`,`p_deps`,`p_size`,`p_id`,`p_total`) VALUES(?,?,?,?,?,?,?,?,?,?)"

                let params = [
                    request.body.u_id,
                    request.body.p_name,
                    request.body.p_price,
                    request.body.p_number,
                    request.body.p_img_index,
                    request.body.p_type,
                    request.body.p_deps,
                    request.body.p_size,
                    request.body.p_id,
                    request.body.p_price * request.body.p_number,

                ]

                db.exec(sql, params, (err, result) => {
                    if (err) {

                        response.json({

                            msg: "加入购物车失败i",
                            status: -1,
                            err: err.message
                        })
                    }
                    if (result.affectedRows >= 1) {
                        response.json({
                            msg: "加入购物车成功!",
                            status: 1
                        })
                    }
                })

            }

        });

    } catch (err) {
        console.log(err)
        response.json({
            msg: "加入失败",
            err: err.message,
            status: -2
        })
    }



})

apiRouter.get("/getcarts", (request, response, next) => {

    let sql = "SELECT * FROM `carts` WHERE u_id=? ";
    let params = [
        request.query.u_id
    ]
    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "拉去购物车列表失败",
                status: -2,
                err: err.message
            })
            return;
        }
        response.json({
            msg: "拉取成功",
            status: 1,
            data: result
        })
    })


})

apiRouter.post("/modify", (request, response, next) => {
    var updateSql = "UPDATE carts SET p_number=?, p_total=p_number*p_price WHERE c_id=? ;";
    let updatePrams = [
        request.body.p_number,
        request.body.c_id
    ]

    db.exec(updateSql, updatePrams, (err, updateReulst) => {
        if (err) {
            response.json({
                msg: "修改失败!",
                status: -1,
                err: err.message
            })

            return;
        }
        if (updateReulst.affectedRows == 1) {
            response.json({
                msg: "修改成功!",
                status: 1
            })
        }
    });

})

apiRouter.post("/modiMoney", (request, response, next) => {
    let sql = "SELECT `p_total` FROM `carts` WHERE `u_id`=?";
    let params = [request.body.u_id];
    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "修改失败!",
                status: -1,
                err: err.message
            })
            return;
        }
        console.log(result)
        if (result.length >= 1) {
            response.json({
                msg: "修改成功m!",
                status: 1,
                data:result
            })
        }
    })

})
apiRouter.post("/delete", async (request, response, next) => {
    let sql = "DELETE FROM `carts` WHERE c_id=? ;";
    let params = [request.body.c_id];

    let result = await db.execAsync(sql, params).catch((err) => {

        response.json({
            msg: "刪除失敗!",
            err: err.message
        })
    })
    if (result.affectedRows == 1) {
        response.json({
            msg: "删除成功",
            status: 1
        })
    } else {
        response.json({
            msg: "删除失败"
        })
    }

})



//暴露apirouter对象
module.exports = {
    apiRouter
}

